package fh.app4stud.mensa.activities;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.*;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import fh.app4stud.mensa.R;
import fh.app4stud.mensa.Start;
import fh.app4stud.mensa.database.MenuDbAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * 
 * User: ifi Date: 30.04.11 Time: 12:46 To change this template use File |
 * Settings | File Templates.
 */
public class LocationsList extends MapActivity {

	private SharedPreferences prefs;
	private TabHost tabhost;
	private ListView listView;
	private MapView mapView;
	List<String> preferredLocations;
	List<GeoPoint> pointsList;
	List<String> cityNames;
	List<String> streetNames;
	List<Integer> houseNr;
	private MenuDbAdapter mDbHelper;
	private Cursor mCursor;
	private String currentLocation;
	private Boolean firstLoad;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.locations_list);

		Context context = getApplicationContext();
		prefs = PreferenceManager.getDefaultSharedPreferences(context);
		preferredLocations = new ArrayList<String>();
		// extracting TabHost
		tabhost = (TabHost) findViewById(android.R.id.tabhost);
		tabhost.setup();

		// extracting ListView
		listView = (ListView) findViewById(R.id.list);
		listView.setEmptyView(findViewById(R.id.empty));
		registerForContextMenu(listView);

		pointsList = new ArrayList<GeoPoint>();
		cityNames = new ArrayList<String>();
		streetNames = new ArrayList<String>();
		houseNr = new ArrayList<Integer>();

		mDbHelper = new MenuDbAdapter(this);
		mDbHelper.open();

		Bundle extras = getIntent().getExtras();

		if (extras != null) {

			firstLoad = extras.getBoolean(SettingsPreferences.FIRST_LOAD);
			String city = extras.getString(SettingsPreferences.PREF_CITY_NAME);
			mCursor = mDbHelper.fetchLocationsByCity(city);
			startManagingCursor(mCursor);
			int lat = mCursor.getColumnIndex(MenuDbAdapter.KEY_LATITUDE);
			int lon = mCursor.getColumnIndex(MenuDbAdapter.KEY_LONGITUDE);
			int loc_name = mCursor.getColumnIndex(MenuDbAdapter.KEY_LOC_NAME);

			if (mCursor.moveToFirst()) {
				while (!mCursor.isAfterLast()) {
					pointsList.add(new GeoPoint(
							(int) (mCursor.getInt(lat) * 1E6), (int) (mCursor
									.getInt(lon) * 1E6)));
					cityNames.add(mCursor.getString(loc_name));
					mCursor.moveToNext();
				}
			}

			// String[] from = new
			// String[]{MenuDbAdapter.KEY_LOC_NAME,MenuDbAdapter.KEY_STREET,
			// MenuDbAdapter.KEY_HOUSE_NR };
			// int[] to = new int[]{R.id.location_name, R.id.location_street,
			// R.id.location_house_number};

			listView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, cityNames));

			mCursor.close();

		}

		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mapView.postInvalidate();

		Resources res = getResources(); // Resource object to get Drawables

		listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			public void onItemClick(AdapterView parent, View view,
					int position, long id) {
				GeoPoint geoPoint = pointsList.get(position);
				if (geoPoint != null) {
					setMapZoomPoint(geoPoint, 12);
					tabhost.setCurrentTab(1);
				}
			}
		});

		tabhost.addTab(tabhost.newTabSpec("List")
				.setIndicator(null, res.getDrawable(R.drawable.ic_tab_list))
				.setContent(new TabHost.TabContentFactory() {
					public View createTabContent(String arg0) {
						return listView;
					}
				}));
		tabhost.addTab(tabhost.newTabSpec("Map")
				.setIndicator(null, res.getDrawable(R.drawable.ic_tab_map))
				.setContent(new TabHost.TabContentFactory() {
					public View createTabContent(String arg0) {
						return mapView;
					}
				}));

		// workaround to correctly setting the tab
		tabhost.setCurrentTab(1);
		tabhost.setCurrentTab(0);

		if(firstLoad) MessageBox("Long click on location opens a menu.");
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenu.ContextMenuInfo menuInfo) {
		if (v.getId() == R.id.list) {

			AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
			// get the name of the city clicked on
			currentLocation = cityNames.get(info.position);

			menu.setHeaderTitle(currentLocation);
			// get all preffered locations
			getAllPrefferedLocations();
			// if the location is already in proffered locations than offer to
			// delete ti
			if (preferredLocations.contains(currentLocation))
				menu.add(Menu.NONE, 1, 0, "Delete from MyLocations");
			else
				menu.add(Menu.NONE, 2, 0, "Save to MyLocations");
			menu.add(Menu.NONE, 3, 0, "See menu");
		}
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {

		int menuItemIndex = item.getItemId();

		switch (menuItemIndex) {
		case 1:
			deletePrefferedLocation(currentLocation);
			break;
		case 2:
			saveToPrefferedLoactions(currentLocation);
			break;
		case 3:
			jumpToMenuView(currentLocation);
			break;
		}
		// get preferences and save to them

		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.location_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.start_item:
			Intent start = new Intent(LocationsList.this, Start.class);
			startActivity(start);
			return true;
		case R.id.settings_item:
			Intent sett = new Intent(LocationsList.this, SettingsPreferences.class);
			startActivity(sett);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	private void setMapZoomPoint(GeoPoint gp, int zoomLevel) {
		mapView.getController().setCenter(gp);
		mapView.getController().setZoom(zoomLevel);
		mapView.postInvalidate();
	}

	private void getAllPrefferedLocations() {
		preferredLocations.clear();
		java.util.Map<String, ?> allPref = prefs.getAll();
		for (String s : new String[] { SettingsPreferences.PREF_LOCATION1,
				SettingsPreferences.PREF_LOCATION2,
				SettingsPreferences.PREF_LOCATION3,
				SettingsPreferences.PREF_LOCATION4 }) {
			String str = (String) allPref.get(s);
			if (str != "" && str != null) {
				preferredLocations.add(str);
			}
		}
	}

	private void getAllPrefferedLocations(String location) {
		java.util.Map<String, ?> allPref = prefs.getAll();
		for (String s : SettingsPreferences.PREFEREDLOCATIONSARRAY) {
			String str = (String) allPref.get(s);
			if (str == null)
				break;
			if (str.equals(location)) {
				SharedPreferences.Editor editor = prefs.edit();
				editor.remove(s);
				editor.commit();
			}
		}
	}

	private void saveToPrefferedLoactions(String location) {
		SharedPreferences.Editor editor = prefs.edit();
		// find first empty spot in prefferd locations
		int index = findFirstEmpty();
		if (index >= 0) {
			editor.putString(SettingsPreferences.PREFEREDLOCATIONSARRAY[index],
					location);
			editor.commit();
		} else {
			MessageBox("Locations list is full. Please delete a location from your list or upgrade to PRO.");
		}
		MessageBox(location + " has been saved to MyLocations");
	}

	public void MessageBox(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

	private void deletePrefferedLocation(String location) {
		getAllPrefferedLocations(location);
		MessageBox(location + " has been removed from MyLocations");
	}

	private void jumpToMenuView(String location) {
		Intent getMenu = new Intent(LocationsList.this, MenusTabWidget.class);
		// send the current location and day trough bundle
		getMenu.putExtra(SettingsPreferences.CURRENT_LOCATION, location);
		getMenu.putExtra(SettingsPreferences.CURRENT_DAY, Start.getCurrentDay());
		startActivity(getMenu);
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false; // To change body of implemented methods use File |
						// Settings | File Templates.
	}

	public int findFirstEmpty() {
		int i = 0;
		java.util.Map<String, ?> allPref = prefs.getAll();
		for (String s : SettingsPreferences.PREFEREDLOCATIONSARRAY) {
			String str = (String) allPref.get(s);
			if (str == "" || str == null) {
				return i;
			}
			i++;
		}
		return -1;
	}
}
